package com.uzykj.modules.blog.web;

import com.google.common.collect.Lists;
import com.uzykj.common.config.Global;
import com.uzykj.common.json.AjaxJson;
import com.uzykj.common.utils.DateUtils;
import com.uzykj.common.utils.StringUtils;
import com.uzykj.common.utils.excel.ExportExcel;
import com.uzykj.common.utils.excel.ImportExcel;
import com.uzykj.core.persistence.Page;
import com.uzykj.core.web.BaseController;
import com.uzykj.modules.blog.entity.BlogNote;
import com.uzykj.modules.blog.entity.BlogReview;
import com.uzykj.modules.blog.service.BlogReviewService;
import com.uzykj.modules.sys.entity.User;
import com.uzykj.modules.sys.security.SystemAuthorizingRealm;
import com.uzykj.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Map;

/**
 * @author ghostxbh
 * @date 2020/7/9
 * 博客评论Controller
 */
@Controller
@RequestMapping(value = "${adminPath}/blog/review")
public class BlogReviewController extends BaseController {
    @Autowired
    private BlogReviewService blogReviewService;

    @ModelAttribute
    public BlogReview get(@RequestParam(required = false) String id) {
        BlogReview entity = null;
        if (StringUtils.isNotBlank(id)) {
            entity = blogReviewService.get(id);
        }
        if (entity == null) {
            entity = new BlogReview();
        }
        return entity;
    }

    /**
     * 评论列表页面
     */
    @RequiresPermissions("blog:review:list")
    @RequestMapping(value = {"list", ""})
    public String list() {
        return "modules/blog/review/blogReviewList";
    }

    /**
     * 评论列表数据
     */
    @ResponseBody
    @RequiresPermissions("blog:review:list")
    @RequestMapping(value = "data")
    public Map<String, Object> data(BlogReview label, HttpServletRequest request, HttpServletResponse response, Model model) {
        SystemAuthorizingRealm.Principal principal = UserUtils.getPrincipal();
        String id = principal.getId();
        BlogNote blogNote = new BlogNote();
        blogNote.setCreateBy(new User(id));
        label.setNote(blogNote);
        Page<BlogReview> page = blogReviewService.findPage(new Page<BlogReview>(request, response), label);
        return getBootstrapData(page);
    }

    /**
     * 查看，增加，编辑评论
     */
    @RequiresPermissions(value = {"blog:review:view", "blog:review:add", "blog:review:edit"}, logical = Logical.OR)
    @RequestMapping(value = "form")
    public String form(BlogReview label, Model model) {
        model.addAttribute("label", label);
        return "modules/blog/review/blogReviewForm";
    }

    /**
     * 保存评论
     */
    @ResponseBody
    @RequiresPermissions(value = {"blog:review:add", "blog:review:edit"}, logical = Logical.OR)
    @RequestMapping(value = "save")
    public AjaxJson save(BlogReview label, Model model, RedirectAttributes redirectAttributes) throws Exception {
        AjaxJson j = new AjaxJson();
        if (!beanValidator(model, label)) {
            j.setSuccess(false);
            j.setMsg("非法参数！");
            return j;
        }

        //新增或编辑表单保存
        blogReviewService.save(label);//保存
        j.setSuccess(true);
        j.put("label", label);
        j.setMsg("保存商品类型成功");
        return j;
    }

    /**
     * 删除评论
     */
    @ResponseBody
    @RequiresPermissions("blog:review:del")
    @RequestMapping(value = "delete")
    public AjaxJson delete(BlogReview label, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        blogReviewService.delete(label);
        j.setSuccess(true);
        j.setMsg("删除商品类型成功");
        return j;
    }

    /**
     * 批量删除评论
     */
    @ResponseBody
    @RequiresPermissions("blog:review:del")
    @RequestMapping(value = "deleteAll")
    public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        String idArray[] =ids.split(",");
        for(String id : idArray){
            blogReviewService.delete(blogReviewService.get(id));
        }
        j.setMsg("删除评论表单成功");
        return j;
    }

    /**
     * 导出excel文件
     */
    @ResponseBody
    @RequiresPermissions("blog:review:export")
    @RequestMapping(value = "export", method= RequestMethod.POST)
    public AjaxJson exportFile(BlogReview label, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        try {
            String fileName = "评论表单"+ DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<BlogReview> page = blogReviewService.findPage(new Page<BlogReview>(request, response, -1), label);
            new ExportExcel("评论表单", BlogReview.class).setDataList(page.getList()).write(response, fileName).dispose();
            j.setSuccess(true);
            j.setMsg("导出成功！");
            return j;
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导出评论表单记录失败！失败信息："+e.getMessage());
        }
        return j;
    }

    /**
     * 导入Excel数据

     */
    @RequiresPermissions("blog:review:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
        try {
            int successNum = 0;
            int failureNum = 0;
            StringBuilder failureMsg = new StringBuilder();
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<BlogReview> list = ei.getDataList(BlogReview.class);
            for (BlogReview blogReview : list){
                try{
                    blogReviewService.save(blogReview);
                    successNum++;
                }catch(ConstraintViolationException ex){
                    failureNum++;
                }catch (Exception ex) {
                    failureNum++;
                }
            }
            if (failureNum>0){
                failureMsg.insert(0, "，失败 "+failureNum+" 条评论表单记录。");
            }
            addMessage(redirectAttributes, "已成功导入 "+successNum+" 条评论表单记录"+failureMsg);
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入评论表单失败！失败信息："+e.getMessage());
        }
        return "redirect:"+ Global.getAdminPath()+"/blog/review/?repage";
    }

    /**
     * 下载导入评论表单数据模板
     */
    @RequiresPermissions("blog:review:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "评论表单数据导入模板.xlsx";
            List<BlogReview> list = Lists.newArrayList();
            new ExportExcel("评论表单数据", BlogReview.class, 1).setDataList(list).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
        }
        return "redirect:"+Global.getAdminPath()+"/blog/review/?repage";
    }
}
